//
//  YZMDrawViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/1.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMDrawViewController.h"
#import "YZMHintInputView.h"
#import "UIViewController+Utils.h"
#import "YZMRecommandView.h"
#import "YZMAlertView.h"
#import "NSNumber+Utils.h"
#import "YZClient.h"
#import "YZMCardShowView.h"
#import "YZMCardChooseView.h"
#import "YZMBankCardService.h"
#import <BlocksKit/UIControl+BlocksKit.h>
#import "YZMDelayCharge.h"

#define WS(weakSelf) __weak __typeof(&*self)weakSelf = self;

@interface YZMDrawViewController()<UITextFieldDelegate>

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UILabel *balanceLB;
@property (nonatomic, strong) YZMHintInputView *amountInputView;
@property (nonatomic, strong) YZMHintInputView *passwordInputView;
@property (nonatomic, strong) UIButton *submitBT;
@property (nonatomic, strong) YZMBankCardModel *bankCard;
@property (nonatomic, strong) YZMCardShowView *cardView;
@property (nonatomic, strong) YZMCardChooseView *cardChooseView;
@property (nonatomic, strong) NSArray *bankCardList;
@property (nonatomic, assign) BOOL addFlag;
@property (nonatomic, strong) UIView *balanceView;
@property (nonatomic, strong) UILabel *availMoneyLB;
@property (nonatomic, strong) UILabel *deferMoneyLB;

@end


@implementation YZMDrawViewController

- (instancetype)init{
    
    self = [super init];
    if (self) {
        
        self.hidesBottomBarWhenPushed = YES;
        self.title = @"账户提现";
    }
    return self;
}

- (void)viewDidLoad{
    
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self createObjects];
    [self registerForKeyboardAutoWithBottomView:_bottomView];
    [self getFreezeMoney];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bankCardParamInit) name:YZMUserBankCardUpdateNotification object:nil];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self bankCardParamInit];
}

#pragma mark -- param init

- (void)bankCardParamInit{
    
    NSArray *list = YZMUserServiceInstance.user.bankCardList;
    
    if (list.count == 0) {
        
        self.bankCardList = nil;
        return;
    }
    
    if (self.addFlag) {
        
        if (list.count > self.bankCardList.count) {
            self.bankCardList = list;
            self.addFlag = NO;
            self.cardChooseView.cardArray = self.bankCardList;
            self.cardChooseView.selectedIndex = [self.bankCardList indexOfObject:self.bankCard];
            [self.cardChooseView show];
        }
        return;
    }
    
    self.bankCardList = list;
    self.bankCard = self.bankCardList[0];
    if (self.bankCardList.count != 1) {
        
        for (YZMBankCardModel *model in self.bankCardList) {
            
            if (model.defaultFlag) {
                
                self.bankCard = model;
                break;
            }
        }
    }
    
    [self refreshView];
}

#pragma mark -- network

- (void)submitDrawRequest{
    
    [YZClient rd_submitDrawRequestWithBankCardID:self.bankCard.cid andMoney:[self.amountInputView.textField.text trimSpace] andDrawPassword:self.passwordInputView.textField.text success:^(NSURLResponse *task, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [YZMUserServiceInstance fetchUserAssetsInfo];
            [MBProgressHUD showMessage: @"提现申请成功"];
            
            //交易成功
            [YZMHCMInstance pushAfterRootWithName:@"fundDetail" andParams:@{@"fundType":@(YZS_FUND_TYPE_FOR_WITHDRAW)} atIndex:self.tabBarController.selectedIndex];
            
        }else{
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];
}


#pragma mark -- event

- (void)forgotButtonPressed:(UIButton *)sender{
    
    [YZMHCMInstance pushViewControllerWithName:@"forgetWdPwd" andParams:nil];
}

- (void)drawButtonPressed:(UIButton *)sender{
    
    //判断金额
    if ([ @(0.0) isEqualGreaterThanDouble: [self.amountInputView.textField.text doubleValue]]) {
        
        [MBProgressHUD showMessage:@"提现金额不可为零"];
        return;
    }
    
    //银行卡未选择
    if (!self.bankCard) {
        
        [MBProgressHUD showMessage:@"请先添加银行卡"];
        return;
    }
    
    if ([self.passwordInputView.textField.text yz_isWithdrawPwdCode]) {
        [self submitDrawRequest];
    } else {
        [MBProgressHUD showMessage:@"提现密码为6位数字"];
        return;
    }
    
}

- (void)textValueChanged:(UITextField *)field{
    
    if ([field isEqual:self.amountInputView.textField]) {
        
        if ([field.text isEqualToString:@"."]) {
            
            /*第一位为.时，变更为0.*/
            field.text = @"0.";
        }
    }
    
    [self refreshSubmitButton];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if ([textField isEqual:self.amountInputView.textField]) {
        
        if (!string || string.length == 0) {
            
            return YES;
        }
        
        if ( [@([textField.text doubleValue]) isGreaterThanDouble:10000000]) {
            
            return NO;
        }
        
        if ([string isEqualToString:@"."]) {
            
            NSRange range = [textField.text rangeOfString:@"."];
            if (range.length != 0) {
                return FALSE;
            }
            
        }else{
            
            NSRange range = [textField.text rangeOfString:@"."];
            if( range.length != 0 && textField.text.length - range.location >2){
                
                return false;
            }
        }
    }
    
    return YES;
}

#pragma mark -- refresh ui

- (void)refreshSubmitButton{
    
    if (self.amountInputView.textField.text.length > 0 && self.passwordInputView.textField.text.length > 5) {
        self.submitBT.layer.borderWidth=0.0;
        self.submitBT.enabled = YES;
        
    }else{
        self.submitBT.layer.borderWidth=1.0;
        self.submitBT.enabled = NO;
    }
}


#pragma mark -- ui

- (void)refreshView{
    
    self.cardView.card = self.bankCard;
}

- (void)createObjects{
    
    WS(ws)
    
    _bottomView = [UIView new];
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.right.bottom.equalTo(self.view);
        maker.height.mas_equalTo(0);
    }];
    
    UIScrollView *bgSV = [UIScrollView new];
    bgSV.backgroundColor = [UIColor clearColor];
    bgSV.bounces = NO;
    bgSV.showsVerticalScrollIndicator = NO;
    [self.view addSubview:bgSV];
    [bgSV mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.left.top.right.equalTo(ws.view);
        maker.bottom.equalTo(_bottomView.mas_top);
    }];
    
    UIView *containerView = [UIView new];
    containerView.backgroundColor = [UIColor clearColor];
    [bgSV addSubview:containerView];
    [containerView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.edges.equalTo(bgSV);
        maker.width.equalTo(bgSV);
    }];
    
    self.balanceView = [UIView new];
    self.balanceView.backgroundColor = [YZMAppStyle colorForMain];
    [containerView addSubview:self.balanceView];
    [self.balanceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(containerView);
        make.right.equalTo(containerView);
    }];
    
    UIView *lineView = [YZMAppStyle splitLine];
    [self.balanceView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(self.balanceView);
    }];
    
    self.balanceLB = [YZMAppStyle labelWithFont:[YZMAppStyle fontWithSize:30] andColor:[YZMAppStyle colorForIconColor]];
    self.balanceLB.textAlignment = NSTextAlignmentCenter;
    self.balanceLB.text = @(YZMUserServiceInstance.user.assets.balance).decimalr02fString;
    [self.balanceView addSubview:self.balanceLB];
    [self.balanceLB mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.top.equalTo(self.balanceView).offset(20);
        maker.centerX.equalTo(self.balanceView);
    }];
    
    UILabel *allMoneyLB = [YZMAppStyle labelWithMediumLightGray];
    allMoneyLB.text = @"总余额（￥）";
    [self.balanceView addSubview:allMoneyLB];
    [allMoneyLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(ws.balanceLB.mas_bottom).offset(7);
        make.centerX.equalTo(self.balanceView);
    }];
    
    UIView *middleLine  = [YZMAppStyle splitLine];
    [self.balanceView addSubview:middleLine];
    middleLine.backgroundColor = [YZMAppStyle colorforLineAvailMoney];
    [middleLine mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(39);
        make.top.equalTo(allMoneyLB.mas_bottom).offset(30);
        make.centerX.equalTo(ws.balanceView);
        make.width.mas_equalTo(1);
    }];
    
    UIView *leftView = [UIView new];
    [self.balanceView addSubview:leftView];
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(48);
        make.left.equalTo(ws.balanceView);
        make.top.equalTo(middleLine);
        make.width.mas_equalTo((ScreenWidth-1)/2);
        make.bottom.equalTo(ws.balanceView).offset(-20);
    }];
    
    UIView *rightView = [UIView new];
    [self.balanceView addSubview:rightView];
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.top.bottom.width.equalTo(leftView);
        make.right.equalTo(ws.balanceView);
    }];
    
    UILabel *availLB = [YZMAppStyle labelWithFont:[YZMAppStyle fontWithSize:18] andColor:[YZMAppStyle colorForWhite]];
    [leftView addSubview:availLB];
    availLB.text = @"可提余额";
    [availLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(leftView);
        make.top.equalTo(leftView);
    }];
    
    self.availMoneyLB = [YZMAppStyle labelWithMediumWhite];
    [leftView addSubview:self.availMoneyLB];
    [self.availMoneyLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(availLB);
        make.top.equalTo(availLB.mas_bottom).offset(12);
    }];
    
    UIButton *deferBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightView addSubview:deferBtn];
    [deferBtn setImage:[UIImage imageNamed:@"icon_explain_button"] forState:UIControlStateNormal];
    [deferBtn setTitle:@"应缴递延费" forState:UIControlStateNormal];
    deferBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [deferBtn addTarget:self action:@selector(deferExplain) forControlEvents:UIControlEventTouchUpInside];
    [deferBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(rightView);
        make.width.equalTo(rightView);
        make.centerX.equalTo(rightView);
    }];
    
    self.deferMoneyLB = [YZMAppStyle labelWithMediumWhite];
    [rightView addSubview:self.deferMoneyLB];
    [self.deferMoneyLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(deferBtn);
        make.top.equalTo(ws.availMoneyLB);
    }];
    
    self.amountInputView = [YZMHintInputView new];
    self.amountInputView.textField.placeholder = @"最低100元起提，每日限提3次";
    self.amountInputView.textField.delegate = self;
    self.amountInputView.textField.keyboardType = UIKeyboardTypeDecimalPad;
    self.amountInputView.inputLabel.text = @"提现金额";
    
    self.amountInputView.lineTopView.hidden=NO;
    self.amountInputView.lineBottomView.hidden=NO;
    
    [self.amountInputView.textField addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [containerView addSubview:_amountInputView];
    [self.amountInputView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.top.equalTo(ws.balanceView.mas_bottom).offset(15);
        maker.left.right.equalTo(containerView);
        maker.height.mas_equalTo(44);
    }];
    
    UILabel *label = [YZMAppStyle labelWithLargeGray];
    label.text = @"元";
    
    UILabel *bankCardStringLB = [YZMAppStyle labelWithMediumLightGray];
    bankCardStringLB.text = @"提现银行卡";
    [containerView addSubview:bankCardStringLB];
    [bankCardStringLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.amountInputView.mas_bottom).offset(20);
        make.left.equalTo(containerView).offset(15);
    }];
    
    self.cardView = [YZMCardShowView new];
    self.cardView.card = nil;
    [containerView addSubview:self.cardView];
    [self.cardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bankCardStringLB.mas_bottom).offset(15);
        make.left.right.equalTo(containerView);
    }];
    
    __weak __typeof(&*self)weakSelf = self;
    [self.cardView bk_addEventHandler:^(id sender) {
        
        if (self.bankCardList.count == 0) {
            [YZMHCMInstance pushViewControllerWithName:@"addBankCard" andParams:nil];
            return;
        }
        
        if (!self.cardChooseView) {
            
            self.cardChooseView = [YZMCardChooseView new];
            self.cardChooseView.chooseAction = ^(NSInteger index){
                
                weakSelf.bankCard = weakSelf.bankCardList[index];
                [weakSelf refreshView];
            };
            self.cardChooseView.addAction = ^{
                
                weakSelf.addFlag = YES;
                [YZMHCMInstance pushViewControllerWithName:@"addBankCard" andParams:nil];
            };
        }
        self.cardChooseView.cardArray = self.bankCardList;
        self.cardChooseView.selectedIndex = [self.bankCardList indexOfObject:self.bankCard];
        [self.cardChooseView show];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    self.passwordInputView = [YZMHintInputView new];
    self.passwordInputView.textField.delegate = self;
    self.passwordInputView.textField.keyboardType = UIKeyboardTypeNumberPad;
    self.passwordInputView.inputLabel.text = @"提现密码";
    self.passwordInputView.textField.secureTextEntry =YES;
    self.passwordInputView.textField.placeholder = @"请输入提现密码";
    
    self.passwordInputView.lineTopView.hidden=NO;
    self.passwordInputView.lineBottomView.hidden=NO;
    
    [self.passwordInputView.textField addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingChanged];
    [containerView addSubview:self.passwordInputView];
    [self.passwordInputView mas_makeConstraints:^(MASConstraintMaker *maker){
        
        maker.top.equalTo(self.cardView.mas_bottom).offset(15);
        maker.left.right.equalTo(containerView);
        maker.height.mas_equalTo(44);
    }];
    
    UIButton *forgotPwBT = [UIButton new];
    [forgotPwBT setTitle:@"忘记密码" forState:UIControlStateNormal];
    [forgotPwBT setTitleColor:[YZMAppStyle colorForIconColor] forState:UIControlStateNormal];
    [forgotPwBT.titleLabel setFont:[YZMAppStyle mediumSizeFont]];
    [forgotPwBT addTarget:self action:@selector(forgotButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.passwordInputView appendRightWidget:forgotPwBT isShowSegmentLine:YES];
    
    self.submitBT = [YZMAppStyle NewsubmitButton];
    [containerView addSubview:self.submitBT];
    [self.submitBT setTitle:@"确定" forState:UIControlStateNormal];
    [self.submitBT addTarget:self action:@selector(drawButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.submitBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordInputView.mas_bottom).offset(30);
        make.left.equalTo(containerView).offset(15);
        make.right.equalTo(containerView).offset(-15);
        
    }];
    
    UILabel *hintTitleLB = [YZMAppStyle labelWithSmallLightGray];
    hintTitleLB.numberOfLines = 0;
    hintTitleLB.text = @"提现处理时间：\n";
    hintTitleLB.textAlignment = NSTextAlignmentCenter;
    [containerView addSubview:hintTitleLB];
    [hintTitleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(ws.submitBT.mas_bottom).offset(37);
        make.left.equalTo(containerView).with.offset(15);
        make.right.equalTo(containerView).with.offset(-15);
    }];
    
    NSString *hintStr = [NSString stringWithFormat:@"白天：上午11:00 — 下午16:00 (当天17:00前处理)\n晚上：下午16:00 — 次日11:00 (次日12:00前处理)\n具体到账时间以银行为准，节假日延后处理"];
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineSpacing = 5; //设置行间距
    paraStyle.alignment = NSTextAlignmentCenter;
    NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:hintStr attributes: @{NSParagraphStyleAttributeName:paraStyle}];
    UILabel *hintLB = [YZMAppStyle labelWithSmallLightGray];
    hintLB.numberOfLines = 0;
    hintLB.attributedText = attStr;
    [containerView addSubview:hintLB];
    [hintLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(hintTitleLB.mas_bottom);
        make.left.equalTo(containerView).with.offset(15);
        make.right.equalTo(containerView).with.offset(-15);
        make.bottom.equalTo(containerView).offset(-20);
    }];
}

-(void)deferExplain{
    
    YZMRecommandView *view = [YZMRecommandView new];
    view.titleLabel.text = @"应缴递延费";
    view.contentLabel.text = @"当前交易日14:50之后，未点卖策略（含停牌股）将自动冻结下一交易日的递延费，收盘前点卖可解冻。";
    [view showInView:self.navigationController.view];
}

-(void)getFreezeMoney{
    
    WS(ws)
    [YZClient freezemoney_success:^(NSURLResponse *task, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            ws.deferMoneyLB.text = @([topModel.data doubleValue]).p02fString;
            if (![@([@(YZMUserServiceInstance.user.assets.balance).r2fString doubleValue] - [@([topModel.data doubleValue]).p02fString doubleValue]) isGreaterThanDouble:0]) {
                
                
                
                ws.availMoneyLB.text = @(0).decimalr02fString;
            }else{
                
                ws.availMoneyLB.text = @([@(YZMUserServiceInstance.user.assets.balance).r2fString doubleValue] - [@([topModel.data doubleValue]).p02fString doubleValue]).decimalr02fString;
            }
        }else{
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

@end
